package com.example.nettyclient.netty;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : zjs
 * @Date: 2021/4/29 18:17
 * Description:
 */

import com.example.nettyclient.respone.ResponseResult;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户端处理器
 **/
@Slf4j
@Setter
@Getter
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private ResponseResult responseResult;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端Active .....");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("客户端收到消息: {}", msg.toString());
        //获得服务端返回参数方法一，推荐使用
        ctx.channel().attr(AttributeKey.valueOf("Attribute_key")).set(msg);
        //获得服务端返回参数方法二,有什么不同？或者问题
        this.responseResult = ResponseResult.success(msg.toString(), "100");
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}